import React, { useEffect, useState, forwardRef, useImperativeHandle } from 'react';
import styles from './index.module.less';
import classnames from 'classnames';
import { deepClone } from '@/utils/index';
import { FilterAreaProps, OptionsListItem, FilterOptionsItem, BackData } from './interface.d';

const FilterArea: React.FC<FilterAreaProps> = forwardRef((props, ref) => {
  const { onFilterChange } = props;
  const [data, setData] = useState(props.data || []);
  const [activeIndex, setActiveIndex] = useState<number | undefined>(undefined);

  useEffect(() => {
    if (props.values) {
      return setDataformProps();
    }
    const newData = deepClone(props.data);
    // 设置第一个选项为默认选项
    newData.forEach((item: OptionsListItem) => {
      item.options[0].active = true;
    });
    setData(newData);
  }, [props.values]);

  const setDataformProps = () => {
    const cloneData = deepClone(data);
    for (const key in props.values) {
      cloneData.forEach((item) => {
        if (item.value === key) {
          const targetOption = item.options?.find((op) => op.value === props.values[key]);
          if (targetOption) {
            item.selectedOption = targetOption;
            item.active = true;
          }
        }
      });
    }
    setData(cloneData);
  };

  const handleFilterItemClick = (index: number) => {
    setActiveIndex(activeIndex === undefined ? index : undefined);
  };

  const handleOptionItemClick = (index: number) => {
    if (activeIndex === undefined) return;
    const newData = deepClone(data);
    newData[activeIndex].options.forEach((item: FilterOptionsItem, optIndex: number) => {
      if (index === optIndex) {
        item.active = true;
        newData[activeIndex].selectedOption = item;
      } else {
        item.active = false;
      }
    });
    setData(newData);
    setActiveIndex(undefined);
    const formatData = {};
    newData.forEach((item: OptionsListItem) => {
      formatData[item.value] = item.selectedOption?.value;
    });
    setTimeout(() => {
      onFilterChange && onFilterChange(formatData as BackData);
    });
  };

  // 提供给外部组件，用来获取值的对外方法
  const getValues = () => {
    const formatData = {};
    data.forEach((item: OptionsListItem) => {
      formatData[item.value] = item.selectedOption?.value;
    });
    return formatData;
  };

  useImperativeHandle(ref, () => ({
    getValues
  }));

  return (
    <div className={classnames(styles.wrap, styles.borderBottom)}>
      <ul className={styles.filterList}>
        {
          data.map((item, index) => (
            <li
              className={classnames(styles.filterItem)}
              key={index}
              onClick={() => handleFilterItemClick(index)}
            >
              <span className={classnames(styles.label, item.selectedOption ? styles.active : '')}>
                {item.selectedOption?.label || item.label}
              </span>
              <span className={classnames(styles.iconWrap, activeIndex === index && activeIndex !== undefined ? styles.active : '')}>
                <i className={classnames('icon iconfont', styles.filterItemIcon)}>&#xe6e7;</i>
              </span>
            </li>
          ))
        }
      </ul>
      <ul className={classnames(styles.filterOptions, styles.borderBottom, activeIndex === undefined ? styles.hide : '')}>
        {
          activeIndex !== undefined &&
          data[activeIndex].options?.map((item: FilterOptionsItem, index: number) => (
            <li
              className={classnames(styles.optionItem, item.active ? styles.active : '')}
              key={index}
              onClick={() => handleOptionItemClick(index)}
            >
              {item.label}
            </li>
          ))
        }
      </ul>
    </div>
  );
});

export default FilterArea;
export { FilterAreaProps, OptionsListItem, FilterOptionsItem, BackData };